import './index.less';
import * as echarts from 'echarts';
import {useEffect, useRef, useState} from "react";
import useAppState from "../../store";
import COLOR_SCALES_ARRAY from "../../constant.ts"
import {isEmpty} from "lodash";

const HeatMapUpGraph = () => {
    // 使用 useRef 持久化保存 ECharts 实例
    const chartRef = useRef<echarts.ECharts | null>(null);
    const chartContainerRef = useRef<HTMLDivElement | null>(null);
    const {allTopicWord} = useAppState();
    const option = {
        tooltip: {
            trigger: 'item',
            position: 'top',
            formatter: function (params) {
                let content = "";
                if (params.seriesType === "bar") {
                    content = `${params.marker}<span style="margin-left: 2px">${params.name}</span><span style="margin-left: 20px">${params.value}</span>`
                } else {
                    content = params.data[1] + '<br/>' + `
                    ${params.marker}
                    <span style="margin-left: 2px">${params.data[0]}</span>
                    <span style="margin-left: 20px">${params.data[2]}</span>`;
                }
                return content;
            }
        },
        title: [
            // 左侧标题（绑定到 grid[0]）
            {
                text: 'Words evolution matrix',
                textStyle: {
                    fontSize: 14,
                    fontFamily: 'Arial, sans-serif',
                    fontWeight: 'bold',
                },
                left: '0px',
                top: '0px'
            },
            // 右侧标题（绑定到 grid[1]）
            {
                text: 'Count accumulation of Words',
                textStyle: {
                    fontSize: 14,
                    fontFamily: 'Arial, sans-serif',
                    fontWeight: 'bold',
                },
                left: '0px',
                top: '200px'
            }
        ],
        dataZoom: [
            {
                show: true,
                type: 'slider',
                left: '80',
                right: '55',
                height: '20px',
                bottom: '10px',
                start: 20,
                end: 30,
                realtime: true,
                xAxisIndex: [0, 1]
            },
            {
                type: 'inside',
                realtime: true,
                xAxisIndex: [0, 1]
            }
        ],
        grid: [
            {
                left: '80',
                height: '150',
                top: '35',
                right: '55',
                // show:true,
                // backgroundColor: 'red',
            },
            // 右侧 grid（占 50% 宽度）
            {
                left: '80',
                top: '230px',
                bottom: '50px',
                right: '55'
                // show:true,
                // backgroundColor: 'red',
            }
        ],
        xAxis: [
            {
                type: 'category',
                data: [],
                gridIndex: 0,
                // boundaryGap: false
            },
            {
                type: 'category',
                data: [],
                gridIndex: 1,
                // boundaryGap: false
            }
        ],
        yAxis: [
            // 左侧 y 轴（绑定到 grid[0]）
            {
                type: 'category',
                data: [],
                gridIndex: 0
            },
            // 右侧 y 轴（绑定到 grid[1]）
            {
                type: 'value',
                gridIndex: 1
            }
        ],
        visualMap: {
            min: -20,
            max: 80,
            calculable: true,
            orient: 'vertical',
            right: '0px',
            top: '35px',
            // 灰蓝色渐变配置
            inRange: {
                color: ["rgb(208,209,230)", "rgb(166,189,219)", "rgb(116,169,207)", "rgb(43,140,190)", "rgb(4,90,141)"],
            },
            // 可选：文本标签样式
            textStyle: {
                color: '#333'
            }
        },
        series: [
            {
                name: 'Words evolution',
                type: 'heatmap',
                data: [],
                itemStyle: {
                    borderWidth: 1, // 设置格子的边框宽度
                    borderColor: "#ffffff", // 设置格子的边框颜色
                },
            },
            {
                data: [],
                type: 'bar',
                smooth: true,
                xAxisIndex: 1,
                yAxisIndex: 1, // 使用第一个 x 轴
                barCategoryGap: '1',  // 类目间的柱间距离（适合类目轴）
            }
        ]
    }
    useEffect(() => {
        // 初始化逻辑（仅执行一次）
        if (!chartRef.current && chartContainerRef.current) {
            // 1. 初始化图表
            chartRef.current = echarts.init(chartContainerRef.current);

            // 2. 添加窗口自适应监听
            const resizeHandler = () => chartRef.current?.resize();
            window.addEventListener('resize', resizeHandler);
            // 3. 组件卸载时的清理函数
            return () => {
                window.removeEventListener('resize', resizeHandler);
                chartRef.current?.dispose();
                chartRef.current = null;
            };
        }
    }, []);

    useEffect(() => {
        if (isEmpty(allTopicWord)) return;
        if (chartRef.current) {
            const {width, height} = chartContainerRef.current.getBoundingClientRect();
            const firstGraphTop = 25, graphGap = 50, secondGraphBottom = 50;
            option.grid[0].top = firstGraphTop;
            option.grid[0].height = (height - firstGraphTop - graphGap - secondGraphBottom) * 0.8;
            option.grid[1].top = firstGraphTop + option.grid[0].height + graphGap;
            option.grid[1].bottom = secondGraphBottom;
            option.title[1].top = firstGraphTop + option.grid[0].height + 20

            option.xAxis[0].data = allTopicWord["headMapData"]["column_headers"]
            option.yAxis[0].data = [...allTopicWord["headMapData"]["row_names"]].reverse()
            option.visualMap.min = allTopicWord["headMapData"]["min_value"]
            option.visualMap.max = allTopicWord["headMapData"]["max_value"]
            option.series[0].data = allTopicWord["headMapData"]["data"]

            option.xAxis[1].data = allTopicWord["barData"]["x_data"]
            option.series[1].data = allTopicWord["barData"]["y_data"]
            chartRef.current.setOption(option, {notMerge: true});
        }
    }, [allTopicWord]);
    return (
        <div
            id="HeatMapUpGraph"
            ref={(el) => {
                chartContainerRef.current = el;
            }}
        />
    );
};

export default HeatMapUpGraph;
